const appointmentApi = require('../../api/appointment')
const packageApi = require('../../api/package')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 从上一页传递的预约信息
    appointmentInfo: {
      storeManagerId: null,
      storeManagerName: '',
      selectedDate: '',
      selectedTime: '',
      timeRange: ''
    },
    
    // 套餐列表
    packageList: [],
    selectedPackage: {},
    
    // 备注
    remark: '',
    
    // 加载状态
    loading: false,
    submitting: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('预约套餐页面参数:', options)
    
    // 解析传递的预约信息
    if (options.appointmentInfo) {
      try {
        const appointmentInfo = JSON.parse(decodeURIComponent(options.appointmentInfo))
        console.log('解析的预约信息:', appointmentInfo)
        
        // 格式化日期和时间显示
        const formattedDate = this.formatDate(appointmentInfo.selectedDate)
        const formattedTime = this.formatTimeRange(appointmentInfo.selectedTime)
        const fullTimeDisplay = `${formattedDate} ${formattedTime}`
        
        this.setData({ 
          appointmentInfo: appointmentInfo,
          formattedDate: formattedDate,
          formattedTime: formattedTime,
          fullTimeDisplay: fullTimeDisplay
        })
        
      } catch (error) {
        console.error('解析预约信息失败:', error)
        wx.showToast({
          title: '页面参数错误',
          icon: 'none'
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
        return
      }
    } else {
      console.error('未收到appointmentInfo参数')
      wx.showToast({
        title: '请先选择预约时间',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }
    
    this.loadPackageList()
  },

  /**
   * 加载套餐列表
   */
  async loadPackageList() {
    try {
      this.setData({ loading: true })
      console.log('正在加载套餐列表...')
      
      const response = await packageApi.getAllEnabledPackages()
      console.log('套餐列表响应:', response)
      
      // request工具已经解构了Result对象，直接处理返回的data
      if (response && Array.isArray(response)) {
        const packages = response || []
        this.setData({
          packageList: packages,
          loading: false
        })
        console.log('套餐列表加载完成:', packages)
        
        if (packages.length === 0) {
          wx.showToast({
            title: '暂无可用套餐',
            icon: 'none'
          })
        }
      } else {
        throw new Error('套餐数据格式错误')
      }
    } catch (error) {
      console.error('加载套餐列表失败:', error)
      this.setData({ 
        loading: false,
        packageList: []
      })
      
      let errorMessage = '加载套餐失败'
      if (error.message) {
        if (error.message.includes('网络')) {
          errorMessage = '网络连接失败'
        } else if (error.message.includes('权限')) {
          errorMessage = '访问权限不足'
        } else if (error.message.includes('登录')) {
          errorMessage = '请先登录'
        } else {
          errorMessage = error.message
        }
      }
      
      wx.showToast({
        title: errorMessage,
        icon: 'none'
      })
    }
  },

  /**
   * 获取会员等级样式类
   */
  getMemberLevelClass(memberLevel) {
    switch (memberLevel) {
      case 'VIP1':
        return 'vip1'
      case 'VIP2':
        return 'vip2'
      case 'VIP3':
        return 'vip3'
      default:
        return 'normal'
    }
  },

  /**
   * 选择套餐
   */
  selectPackage(e) {
    const selectedPackage = e.currentTarget.dataset.package
    console.log('选择套餐:', selectedPackage)
    
    this.setData({
      selectedPackage: selectedPackage
    })
  },

  /**
   * 备注输入
   */
  onRemarkInput(e) {
    this.setData({
      remark: e.detail.value
    })
  },

  /**
   * 返回上一页重新选择时间
   */
  goBack() {
    wx.navigateBack()
  },

  /**
   * 提交预约
   */
  async submitAppointment() {
    const { appointmentInfo, selectedPackage, remark } = this.data
    
    // 参数验证
    if (!selectedPackage.id) {
      wx.showToast({
        title: '请选择服务套餐',
        icon: 'none'
      })
      return
    }

    if (!appointmentInfo.storeManagerId || !appointmentInfo.selectedDate || !appointmentInfo.selectedTime) {
      wx.showToast({
        title: '预约信息不完整',
        icon: 'none'
      })
      return
    }

    try {
      this.setData({ submitting: true })
      wx.showLoading({ title: '提交预约...' })
      
      const appointmentData = {
        storeManagerId: appointmentInfo.storeManagerId,
        packageId: selectedPackage.id,
        appointmentDate: appointmentInfo.selectedDate,
        appointmentHour: parseInt(appointmentInfo.selectedTime),
        remark: remark.trim()
      }
      
      console.log('提交预约数据:', appointmentData)
      
      const response = await appointmentApi.createAppointment(appointmentData)
      console.log('预约API响应:', response)
      
      // 对于createAppointment接口，后端返回Result<Void>
      // request工具成功时返回data部分，对于Void类型，data为null
      // 所以response为null表示成功，如果有错误会在catch中处理
      wx.hideLoading()
      wx.showToast({
        title: '预约成功',
        icon: 'success'
      })
      
      console.log('预约成功，准备跳转...')
      
      // 跳转到我的预约页面
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/my-appointments/my-appointments'
        })
      }, 1500)
      
    } catch (error) {
      console.error('提交预约失败:', error)
      wx.hideLoading()
      
      let errorMessage = '预约失败'
      
      // 处理不同类型的错误
      if (error.message) {
        if (error.message.includes('网络')) {
          errorMessage = '网络连接失败，请检查网络设置'
        } else if (error.message.includes('登录')) {
          errorMessage = '登录已过期，请重新登录'
        } else if (error.message.includes('时间段')) {
          errorMessage = '该时间段已被预约，请选择其他时间'
        } else if (error.message.includes('权限')) {
          errorMessage = '权限不足，请联系管理员'
        } else {
          errorMessage = error.message
        }
      }
      
      wx.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
    } finally {
      this.setData({ submitting: false })
    }
  },

  /**
   * 格式化日期显示
   */
  formatDate(dateStr) {
    if (!dateStr) {
      return ''
    }
    
    try {
      const date = new Date(dateStr)
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return dateStr // 返回原始字符串
      }
      
      const month = date.getMonth() + 1
      const day = date.getDate()
      const weekDays = ['日', '一', '二', '三', '四', '五', '六']
      const week = weekDays[date.getDay()]
      
      return `${month}月${day}日 周${week}`
    } catch (error) {
      return dateStr
    }
  },

  /**
   * 格式化时间范围
   */
  formatTimeRange(selectedTime) {
    if (selectedTime === null || selectedTime === undefined || selectedTime === '') {
      return ''
    }
    
    try {
      const hour = parseInt(selectedTime)
      
      // 检查小时是否有效
      if (isNaN(hour) || hour < 0 || hour > 23) {
        return selectedTime ? selectedTime.toString() : ''
      }
      
      return `${hour}:00-${hour + 1}:00`
    } catch (error) {
      return selectedTime ? selectedTime.toString() : ''
    }
  },

  /**
   * 页面分享
   */
  onShareAppMessage() {
    return {
      title: '预约理发服务',
      path: '/pages/index/index'
    }
  }
}) 